package xyz.yuanjilu.service.impl;

import java.io.File;
import java.net.URL;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import xyz.yuanjilu.service.WorkspaceService;

@Service
public class WorkspaceServiceImpl implements WorkspaceService {
	Logger logger= LoggerFactory.getLogger(getClass());
	@Value("${user.home}")
	private String WorkspaceDirectory;
	
	@Override
	public File getWorkspaceDirectory() {
		String root = WorkspaceDirectory+File.separator+ "webspiderWorkspace"+File.separator;
		File workspaceDirectory = new File(root);
		if (!workspaceDirectory.exists()) {
			workspaceDirectory.mkdirs();
		}
		return workspaceDirectory;
	}
	@Override
	public String getPath(String uri) {
		if (uri == null) {
			uri = "";
		}
		StringBuilder sb = new StringBuilder();
		sb.append(WorkspaceDirectory+File.separator+ "webspiderWorkspace");
		if (!uri.startsWith("/")) {
			sb.append(File.separator);
		}
		sb.append(uri.replace('/', File.separatorChar));
		return sb.toString();
	}
	@Override
	public String getPath(String uri, String prefix) {
		if (uri == null) {
			uri = "";
		}
		StringBuilder sb = new StringBuilder();
		if (StringUtils.startsWith(prefix, "file:")) {
			sb.append(prefix.substring(5));
		} else {
			sb.append(WorkspaceDirectory+File.separator+ "webspiderWorkspace");
			if (StringUtils.isNotBlank(prefix)) {
				sb.append(prefix.replace('/', File.separatorChar));
			}
		}
		if (!uri.startsWith("/")) {
			sb.append(File.separator);
		}
		sb.append(uri.replace('/', File.separatorChar));
		return sb.toString();
	}
	
}
